package icu.study.common.security.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import icu.study.common.security.constant.JwtConstant;
import icu.study.common.security.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;


/**
 * @program: spring security
 * @description:
 * @author: 1246263205@qq.com
 * @create: 2020-10-11 18:56
 */
public class JwtFilter extends GenericFilter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //拿到token并转码
        String jwtToken = request.getHeader(JwtConstant.JWT_HEADER);
        if (StringUtils.isNoneBlank(jwtToken)) {
            String token = new String(jwtToken.getBytes("ISO-8859-1"), "UTF-8");
            //将token验证
            DecodedJWT verifier = JwtUtil.verifyToken(token);
            //获取subject，也就是username
            String username = verifier.getSubject();
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(verifier.getClaims().get("authorities").asString()); //获取角色权限
            UsernamePasswordAuthenticationToken tokenBean = new UsernamePasswordAuthenticationToken(username, null, authorities);
            //校验
            SecurityContextHolder.getContext().setAuthentication(tokenBean);
        }
        //让过滤器继续往下走
        filterChain.doFilter(servletRequest, servletResponse);
    }
}